<template>
  <base-page-view class-name="page-container teamPage">
    <view v-if="user" class="head_pain">
      <image src="/static/images/invitation/login_out.png" class="login_out" @click="loginOut" />
      <view class="userInfo">
        <image :src="user.head_img || '/static/images/invitation/logo_dark.png'" class="touxiang" />
        <view class="nick">{{ user.nickname }}</view>
        <view class="userTag">
          <image class="userTagImg" :src="(`/static/images/mine/vip_level_${user.current_member_card_type || 0}.png`)" />
          <view class="userTagTit">{{ getUserLevelName(user.current_member_card_type) }}</view>
        </view>
      </view>
      <view class="totalText">累计团队购买礼包数</view>
      <view class="totalNum">{{ levelData.sangiftCount }}</view>
      <view class="progress_box">
        <span v-if="levelData.role ===0 || levelData.role === 1" class="level_icon_text">普通</span>
        <image v-else class="level_icon" :src="(`/static/images/invitation/lv_${levelData.subdivisionLevel}.png`)" />
        <view class="progress_view">
          <progress :percent="percent" stroke-width="3" activeColor="#DBDFE8" backgroundColor="#57575B" border-radius="10" />
        </view>
        <view v-if="levelData.nextLevelElem">
          <image class="level_icon" :src="levelData.nextLevelElem" />
        </view>
        <view class="buy_txt">{{ levelData.nextLevelText }}</view>
      </view>
    </view>
    <view class="firend_num">我的好友数：{{ firendTotal }}</view>
    <view v-for="(item,index) in invitateList" :key="index" class="invitateList">
      <view class="invitateBox">
        <view class="invitate_userInfo">
          <view class="invitate_touxiang_box">
            <image :src="item.headImg?item.headImg:'/static/images/invitation/logo_dark.png'" class="invitate_touxiang" />
            <view class="invitate_role">
              <view class="invitate_userTag">
                <image class="invitate_userTagImg" :src="(`/static/images/mine/vip_level_${item.role || 0}.png`)" />
                <view class="invitate_userTagTit">{{ getUserLevelName(user.role) }}</view>
              </view>
            </view>
          </view>
          <view class="nickname_box">
            <view class="nickname_view">
              <view class="nickname_text">{{ item.nickname }}</view>
              <image v-if="item.role !==0 && item.role !==1" :src="`/static/images/invitation/glv_${item.subdivisionLevel}.png`" class="vip_level_img" />
            </view>
            <view class="phone_box">
              <view>手机号：{{ item.mobile }}</view>
              <image src="/static/images/commission/phone.png" class="phone" @click="callPhone(item)" />
            </view>
            <view>加入时间：{{ item.registerTime | formatDate }}</view>
          </view>
          <image class="invitate_expand" :src="!item.isShow?'/static/images/invitation/arrow_down.png':'/static/images/invitation/arrow_top.png'" @click="expandItem(item,index)" />
        </view>
        <view v-if="item.isShow" class="invitate_datainfo">
          <view class="datainfo_text">团队已购礼包
            <span class="datainfo_num">{{ item.giftNum.sangiftCount }}</span>
          </view>
          <view>团队未购礼包
            <span class="datainfo_num">{{ item.giftNum.notSangiftCount }}</span>
          </view>
        </view>
      </view>
    </view>
    <view v-if="nomore&&invitateList.length>0" class="nomore">暂无更多好友~</view>
    <view v-if="invitateList.length<1" class="empty_view">
      <image src="/static/images/invitation/empty_img.png" class="empty_img" />
      <view class="tit">暂无好友</view>
    </view>
    <confirm-popup ref="confirm" />
  </base-page-view>
</template>

<script>
import confirmPopup from '@/components/confirmPopup/index'
import { mapGetters, mapActions } from 'vuex'
import './index.scss'
export default {
  components: {
    confirmPopup
  },
  data() {
    return {
      user: '',
      percent: 0,
      levelData: {
        subdivisionLevel: 1
      },
      firendTotal: 0,
      invitateList: [],
      pageNo: 1,
      pageSize: 10,
      nomore: false
    }
  },
  computed: {
    ...mapGetters(['userToken'])
  },
  created() {
  },
  onLoad(option) {
    if (this.userToken) {
      this.initUser()
    } else {
      this.$navigateTo('/pages/login/index', 'redirectTo')
    }
  },
  onShow() {
  },
  onPullDownRefresh() {
    this.pageNo = 1
    this.invitateList = []
    this.nomore = false
    this.initUser()
  },
  onReachBottom() {
    if (this.nomore) return
    this.pageNo += 1
    this.getInvitationList()
  },
  methods: {
    async initUser() {
      await this.GetUserInfo().then(() => {
        this.user = this.$store.state.userInfo
        this.getData()
      })
    //   console.log(this.user)
    },
    async getData() {
      const res = await this.$api.commissionApi.getLevelMy({
        hideLoading: true,
        userId: this.user.uid
      })
      if (res.code === '000000') {
        this.levelData = res.data
        this.getPercent()
        this.getNextLevelElem()
        this.getNextLevelText()
        this.getInvitationList()
      }
    },
    async getInvitationList() {
      const invitate = await this.$api.commissionApi.getMyInvitationListNew({
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        userId: this.user.uid,
        underling: true
      })
      if (invitate.code === '000000') {
        this.firendTotal = invitate.data.total
        setTimeout(function() {
          uni.stopPullDownRefresh()
        }, 500)
        const listArr = invitate.data.list
        if (listArr.length > 0) {
          listArr.forEach(item => {
            item.isShow = false
            item.giftNum = {
              sangiftCount: 0,
              notSangiftCount: 0
            }
          })
        }
        this.invitateList = this.invitateList.concat(listArr)
        if (invitate.data.list.length < this.pageSize) {
          this.nomore = true
        }
        // console.log(invitate)
      }
    },
    expandItem(item, index) {
      this.getUserGiftNum(item, index)
    },
    // 获取用户已购未购礼包数
    async getUserGiftNum(item, index) {
      if (item.isShow) {
        this.invitateList[index].isShow = !item.isShow
        return false
      } else {
        try {
          const { data } = await this.$api.commissionApi.getUserBuyGiftNum({ userId: item.userId })
          this.invitateList[index].giftNum = data
          this.invitateList[index].isShow = !item.isShow
        } catch (error) {
          console.log(error)
        }
      }
    },
    getNextLevelElem() {
      if (this.levelData.role === 1 || this.levelData.role === 0) {
        this.levelData.nextLevelElem = `/static/images/invitation/lv_1.png`
      } else if (this.levelData.role === 2 && this.levelData.subdivisionLevel === 9) {
        // 大区最高级
        this.levelData.nextLevelElem = `/static/images/invitation/lv_1.png`
      } else if (this.levelData.role === 3 && this.levelData.subdivisionLevel === 8) {
        // 董事最高级
        this.levelData.nextLevelElem = ``
      } else {
        this.levelData.nextLevelElem = `${`/static/images/invitation/lv_${this.levelData.subdivisionLevel + 1}.png`}`
        console.log(this.levelData.subdivisionLevel + 1)
      }
      // console.log('inx', this.levelData.nextLevelElem)
    },
    getNextLevelText() {
      if (this.levelData.role === 1 || this.levelData.role === 0) {
        this.levelData.nextLevelText = `购买数达到${this.levelData.nextLevelSangiftCount}升级大区lv1`
      } else if (this.levelData.role === 2 && this.levelData.subdivisionLevel === 9) {
        this.levelData.nextLevelText = `购买数达到${this.levelData.nextLevelSangiftCount}升级董事lv1`
      } else if (this.levelData.role === 3 && this.levelData.nextLevelSangiftCount === 0) {
        this.levelData.nextLevelText = `您已是最高级别`
      } else {
        this.levelData.nextLevelText = `购买数达到${this.levelData.nextLevelSangiftCount}升级lv${this.levelData.subdivisionLevel + 1}`
      }
    },
    getPercent() {
      //  当用户role===3是董事， 且下一等级需达成礼包数位0时，表示该用户等级已达最高
      if (this.levelData.role === 3 && this.levelData.nextLevelSangiftCount === 0) {
        this.percent = 100
      } else {
        this.percent = (this.levelData.sangiftCount / this.levelData.nextLevelSangiftCount) * 100
      }
    },
    getUserLevelName(current_member_card_type) {
      if (!this.user) {
        return '游客'
      }
      let state = '游客'
      switch (this.user.current_member_card_type) {
        case 0:
          state = '碧选会员'
          break
        case 1:
          state = '碧选会员'
          break
        case 2:
          state = '碧选会员'
          break
        case 3:
          state = '碧选会员'
          break
        default:
          break
      }
      return state
    },
    callPhone(item) {
      const mention = uni.getStorageSync('__pboneCall_mention__')
      let msg = ''
      // 如果已经提示过了
      if (mention) {
        msg = '请使用登录的手机号码进行拨打，否则无法通话'
      } else {
        msg = '本次通话将被录音，是否需要继续拨打？（请使用登录的手机号码进行拨打，否则无法通话）'
        uni.setStorageSync('__pboneCall_mention__', true)
      }
      this.$refs.confirm.show({
        title: '提示',
        content: msg,
        yesCb: async() => {
          const res = await this.$api.commissionApi.getPhoneNumber({
            targetUserId: item.userId
          })
          if (res.data && res.data.success === true) {
            uni.makePhoneCall({
              phoneNumber: res.data.virtual_mobile
            })
          } else {
            uni.showToast({
              title: res.data.error_message,
              icon: 'none'
            })
          }
        }
      })
    },
    loginOut() {
      this.$refs.confirm.show({
        title: '提示',
        content: '是否确定退出登录?',
        yesCb: async() => {
          this.LOGOUT_USER()
          uni.setStorageSync('pageAfterLogin', '/pagesMine/teamGiftBag/index')
          uni.reLaunch({ url: '/pages/login/index' })
        }
      })
    },
    ...mapActions(['LOGOUT_USER'])
  }
}
</script>
